using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace SolarWinds.Widgets
{
    public class Label : Widget
    {
        private Texture2D mBackgroundTexture;
        private String mBackgroundAsset;

        #region Properties

        public String Text { get; set; }

        public String BackgroundAsset
        {
            get { return mBackgroundAsset; }
            set
            {
                if (mBackgroundAsset != value)
                {
                    mBackgroundAsset = value;

                    UpdateBackgroundTexture();
                }
            }
        }

        #endregion

        public Label(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            Tabable = false;
        }

        protected internal override void PaintEvent()
        {
            var posX = Position.X;
            var posY = Position.Y;
            Vector2 fontSize = Font.MeasureString(Caption);

            if (mBackgroundTexture != null)
            {
                var destRect = new Rectangle(posX, posY, (int)fontSize.X, (int)fontSize.Y);
                var srcRect = new Rectangle(0, 50, (int)fontSize.X, (int)fontSize.Y);

                SpriteBatch.Draw(mBackgroundTexture, destRect, srcRect, Color.White);
            }

            // strip string
            //String stripCaption = Font.StripString(Width, Caption);

            var fontWidth = (int)Font.MeasureString(Caption).X;

            var pos = new Vector2(ScreenPosition.X,// (Width - fontWidth) / 2;
                                  ScreenPosition.Y);// +(Height - Font.LineHeight) / 2;
            SpriteBatch.DrawString(Font, Caption, pos, TextColor);
        }

        protected override void LoadContent()
        {
            base.LoadContent();

            UpdateBackgroundTexture();
        }

        protected override void UnloadContent()
        {
            if (mBackgroundTexture != null)
            {
                mBackgroundTexture.Dispose();
                mBackgroundTexture = null;
            }

            base.UnloadContent();
        }

        private void UpdateBackgroundTexture()
        {
            if (mBackgroundAsset == null)
            {
                // dispose and unload texture
                if (mBackgroundTexture != null)
                {
                    mBackgroundTexture.Dispose();
                    mBackgroundTexture = null;
                }
            }
            else
            {
                // dispose old texture first
                if (mBackgroundTexture != null)
                {
                    mBackgroundTexture.Dispose();
                }

                mBackgroundTexture = Game.Content.Load<Texture2D>(@"Textures\" + mBackgroundAsset);
            }
        }

    }
}